package com.itheima.controller;

import com.itheima.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("common")
public class CommonController {
    @Value("${reggie.path}")
    String basePath;
    @PostMapping("upload")
    //文件上传
    public R<String> upload(MultipartFile file) throws IOException {
        //判断文件夹是否存在，如不存在则创建
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //获取文件名
        String filename = file.getOriginalFilename();
        String suffix = UUID.randomUUID().toString();
       String filename2 =suffix+filename.substring(filename.lastIndexOf("."));
       //将文件转存到指定路径
       file.transferTo(new File(basePath+filename2));
        return R.success(filename2);
    }
    //文件下载
    @GetMapping("download")
    public void download(HttpServletResponse response,String name) throws Exception {
        //根据路径读取文件
        FileInputStream is=new FileInputStream(basePath+name);
        //将文件读取到网页上显示
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(is, os);
    }
}
